package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		//获取请求源头是说
		origin := c.Request.Header.Get("Origin")
		var headerKeys []string
		for k, _ := range c.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ", ")
		if headerStr != "" {
			//踩坑一次--这里得加上content-type
			headerStr = fmt.Sprintf("content-type, access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		//对origin进行过滤 ---
		if origin != "" {
			// c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Origin", origin)
			c.Header("Access-Control-Allow-Headers", headerStr)
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		//对于复杂请求浏览器会先发送 OPTIONS 来判断是否允许跨域，然后再发送跨域请求
		if method == "OPTIONS" {
			//验证的有效缓存时间：期间不用再发送验证
			c.Header("Access-Control-Max-Age", "172800")
			//https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, content-type")
			c.JSON(http.StatusOK, "Options Request!")
			//不需要继续执行下去了
			return
		}

		c.Next()
	}
}
